import React, {useEffect, useState} from 'react';
import {Button, Col, Form, Input, Menu, message, Modal, Popover, Row, Select, Tabs, Typography,} from 'antd';
import './MainPage.css';
import Teacher from '../teacher/Teacher';
import {useHistory, useLocation} from 'react-router-dom';
import {
    BankOutlined,
    BookOutlined,
    DashboardOutlined,
    EditOutlined,
    IdcardOutlined,
    LogoutOutlined,
    UserOutlined, DatabaseOutlined, SettingOutlined, KeyOutlined, PlusCircleOutlined
} from '@ant-design/icons';
import Course from "../course/course";
import Work from "../work/work";
import App from "../temp";
import cookie from 'react-cookies';
import {conforms} from "lodash";
import services from "../services";


const {TabPane} = Tabs;
const {Text} = Typography;

const MainPage: React.FC = () => {
    const [activeTab, setActiveTab] = useState('app');
    const [resetPasswordVisible, setResetPasswordVisible] = useState(false);
    const [resetForm] = Form.useForm();
    const [currentUserInfo, setCurrentUserInfo] = useState<{
        schoolName: string;
        schoolId: string;
        teacherId: string;
        teacherName: string;
        jobNumber: string;
        roleType: number;
    }>({jobNumber: "", schoolId: "", schoolName: "", teacherId: "", teacherName: "", roleType: 0});
    const history = useHistory();

    const location = useLocation<{
        schoolName: string;
        schoolId: string;
        teacherId: string;
        teacherName: string;
        jobNumber: string;
    }>();
    const params = location.state || {};

    const handleMenuClick = (e: any) => {
        setActiveTab(e.key);
    };

    const handleLogout = () => {
        message.success('登出成功');
        cookie.remove("userInfo")
        history.push({
            pathname: '/login',
        });
    }

    useEffect(() => {
        try {
            let load = cookie.load("userInfo");
            let data = JSON.parse(
                decodeURIComponent(
                    atob(load).split('').map(function (c) {
                        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
                    }).join('')));
            console.log(data)
            setCurrentUserInfo(data);
        } catch (error) {
            // 跳转到登录页面
            window.location.href = '/login';
            message.error("请先登陆系统");

        }
    }, []);

    const content = (
        <div>
            <p><IdcardOutlined/>&nbsp;&nbsp;&nbsp;&nbsp;工号 : {currentUserInfo.jobNumber ?? '未知'}</p>
            <p><UserOutlined/>&nbsp;&nbsp;&nbsp;&nbsp;姓名 : {currentUserInfo.teacherName ?? '未知用户'}</p>
            <p>确认退出系统吗？</p>
            <Button danger onClick={handleLogout}
                    style={{display: "block", margin: "0 auto"}}><LogoutOutlined/>&nbsp;&nbsp;&nbsp;确认</Button>
        </div>
    );

    return (
        <div className="page-container">
            <div className="sidebar-container">
                <Menu mode="inline" defaultSelectedKeys={['app']} onClick={handleMenuClick}>
                    <Menu.Item key="app">主页</Menu.Item>
                    <Menu.Item key="work">作业管理</Menu.Item>
                    <Menu.Item key="course">我的课程</Menu.Item>
                    {
                        currentUserInfo.roleType === 1 && <Menu.Item key="teacher">教师花名册</Menu.Item>
                    }
                </Menu>
            </div>

            <div className="content-container">
                <div>
                    <span style={{fontWeight: 'bold', fontFamily: 'Helvetica, sans-serif'}}>
                      学习过程管理系统
                    </span>
                    <SettingOutlined/>
                </div>
                <Row justify="end" className="user-info">
                    <Col>
                        <div className="user-info-item">
                            <Button
                                icon={<KeyOutlined/>}
                                onClick={() => {
                                    setResetPasswordVisible(true);
                                }}
                            >修改密码</Button>
                        </div>
                    </Col>
                    <Col>
                        <div className="user-info-item">
                            <BankOutlined/>
                            <span className="user-info-text">{currentUserInfo.schoolName ?? '未知学校'}</span>
                        </div>
                    </Col>
                    <Col>
                        <Popover content={content} placement="bottomRight">
                            <div className="user-info-item">
                                <UserOutlined/>
                                <span className="user-info-text">{currentUserInfo.teacherName ?? '未知用户'}</span>
                            </div>
                        </Popover>
                    </Col>
                </Row>
                <Tabs activeKey={activeTab}>
                    <TabPane tab={<span><DashboardOutlined/>主页</span>} key="app">
                        {activeTab === 'app' && <App/>}
                    </TabPane>
                    <TabPane tab={<span><EditOutlined/>作业管理</span>} key="work">
                        {activeTab === 'work' && <Work/>}
                    </TabPane>
                    <TabPane tab={<span><BookOutlined/>我的课程</span>} key="course">
                        {activeTab === 'course' && <Course/>}
                    </TabPane>
                    {
                        currentUserInfo.roleType === 1 &&
                        <TabPane tab={<span><UserOutlined/>教师花名册</span>} key="teacher">
                            {activeTab === 'teacher' && currentUserInfo.roleType === 1 && <Teacher/>}
                        </TabPane>
                    }

                </Tabs>
            </div>

            <Modal
                visible={resetPasswordVisible}
                title="修改密码"
                onCancel={() => {
                    setResetPasswordVisible(false);
                    resetForm.resetFields();
                }}
                cancelText={"取消"}
                okText={"确认"}
                onOk={() => {
                    resetForm.validateFields().then((values) => {
                        services.changePassword(values).then(data => {
                            if (data === true) {
                                message.success("修改密码成功");
                                setResetPasswordVisible(false);
                                history.push({
                                    pathname: '/login',
                                });
                            } else {
                                return;
                            }
                        })
                    }).catch((errorInfo) => {
                        message.error("修改失败");
                    }).finally(() => {
                        resetForm.resetFields();
                    })
                }
                }
            >
                <Form form={resetForm}>
                    <Form.Item label="当前密码" name="oldPassword" rules={[{required: true, message: '请输入当前密码'}]}
                               labelCol={{span: 6}} wrapperCol={{span: 18}}>
                        <Input.Password/>
                    </Form.Item>
                    <Form.Item label="输入新密码" name="newPassword" rules={[{required: true, message: '请输入新密码'}]}
                               labelCol={{span: 6}} wrapperCol={{span: 18}}>
                        <Input.Password/>
                    </Form.Item>
                    <Form.Item label="再次输入新密码" name="newPasswordAgain"
                               rules={[{required: true, message: '请再次输入新密码'}]}
                               labelCol={{span: 6}} wrapperCol={{span: 18}}>
                        <Input.Password/>
                    </Form.Item>
                </Form>
            </Modal>

        </div>


    );
};

export default MainPage;
